package mastermind.view.dialog;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import mastermind.Client;
import mastermind.DataOperator;
import mastermind.Client.MMLoginException;
import mastermind.controller.CancelListener;
import mastermind.game.Player;
import mastermind.view.ClientGUI;

/**
 * A dialog to allow user to register on MM server & log them in automatically
 */
public class RegisterDialog extends JDialog {
	private static final long serialVersionUID = 5681549774161848247L;
	private JTextField firstname, surname, username, phoneNumber;
	private JPasswordField password;
	private ClientGUI cgui;
	private Client client;

	public RegisterDialog(ClientGUI cgui) {
		this.cgui = cgui;
		this.client = cgui.getClient();

		setTitle("register");
		setLayout(new GridBagLayout());
		setModal(true);

		firstname = new JTextField(15);
		surname = new JTextField(15);
		username = new JTextField(15);
		phoneNumber = new JTextField(15);
		password = new JPasswordField(15);

		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.insets = new Insets(5, 5, 5, 5);
		c.weightx = 0.5;
		c.gridy = 0;

		c.gridy++;
		add(new JLabel("username"), c);
		add(username, c);

		c.gridy++;
		add(new JLabel("password"), c);
		add(password, c);

		c.gridy++;
		add(new JLabel("firstname"), c);
		add(firstname, c);
		c.gridy++;

		add(new JLabel("surname"), c);
		add(surname, c);
		c.gridy++;

		add(new JLabel("phone number"), c);
		add(phoneNumber, c);

		JPanel buttons = new JPanel();
		JButton create = new JButton("register");
		create.addActionListener(new RegisterPlayerListener());
		buttons.add(create);

		JButton cancel = new JButton("cancel");
		cancel.addActionListener(new CancelListener(this));
		buttons.add(cancel);

		c.gridy++;
		c.gridwidth = 2;
		add(buttons, c);

		pack();
		// center and display
		setLocationRelativeTo(null);
		setVisible(true);
	}

	/**
	 * @return A Player object built from user entered data
	 */
	public Player getPlayer() {
		return new Player(firstname.getText(), surname.getText(), username
				.getText(), new String(password.getPassword()), phoneNumber
				.getText());
	}

	/**
	 * Records a user as having registered locally
	 * 
	 * @param username
	 *            Username of registered user
	 */
	private void addLocalUser(String username) {
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(
					new FileWriter(DataOperator.LOCAL_LOG, true));
			bw.write(username + "\n");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bw != null) {
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/** Handles registering with user entered details & logs user in */ 
	class RegisterPlayerListener implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {
			if (username.getText().isEmpty()) {
				JOptionPane.showMessageDialog(RegisterDialog.this,
						"invalid username", "you must enter a username",
						JOptionPane.ERROR_MESSAGE);
			}
			
			Player p = getPlayer();
			if (client.register(p)) {
				// record registration in local users log
				addLocalUser(p.getUsername());
				
				// attempt to login new user
				try {
					client.login(p.getUsername(), p.getPassword());
					cgui.setLoggedIn(true);
					cgui.setCurrentUser(p.getUsername());
				} catch (MMLoginException e) {
					cgui.errorMessage(e.getMessage(), "error logging in");
				}
			} else {
				cgui.errorMessage("error registering", "error registering");
			}
			RegisterDialog.this.dispose();
		}

	}
}
